package com.xty.xtyle.picture;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.DialogFragment;


import com.xty.xtyle.MainActivity;
import com.xty.xtyle.R;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.WeakHashMap;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;

public class PickPhotoDialog extends DialogFragment {

    public static int SELECT_PIC_BY_TACK_PHOTO = 0x3;

    View accountEmpty;
    TextView accountCamera;
    TextView accountPhoto;
    TextView accountCancel;

    private Uri imageUri;
    private String imagePath;
    private CallBack callBack;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Window window = getDialog().getWindow();
        View view = inflater.inflate(R.layout.dialog_choose_camera_photo, ((ViewGroup) window.findViewById(android.R.id.content)), false);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//注意此处
        window.setLayout(-1, -2);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        accountEmpty = view.findViewById(R.id.accountEmpty);
        accountCamera = view.findViewById(R.id.accountCamera);
        accountPhoto = view.findViewById(R.id.accountPhoto);
        accountCancel = view.findViewById(R.id.accountCancel);

        accountEmpty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        accountCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        accountCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goCamera();
            }
        });
        accountPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goGallery();
            }
        });

    }

    //拍照
    void goCamera() {
        // 创建File对象，用于存储拍照后的图片
        //存放在手机SD卡的应用关联缓存目录下
        File outputImage = new File(getActivity().getExternalFilesDir(null), (new Date().getTime()) + ".jpg");
       /* 从Android 6.0系统开始，读写SD卡被列为了危险权限，如果将图片存放在SD卡的任何其他目录，
          都要进行运行时权限处理才行，而使用应用关联 目录则可以跳过这一步
        */
        imagePath = outputImage.getPath();
        Log.d("FlutterPush", imagePath);
        /*
           7.0系统开始，直接使用本地真实路径的Uri被认为是不安全的，会抛 出一个FileUriExposedException异常。
           而FileProvider则是一种特殊的内容提供器，它使用了和内 容提供器类似的机制来对数据进行保护，
           可以选择性地将封装过的Uri共享给外部，从而提高了 应用的安全性
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //大于等于版本24（7.0）的场合
            imageUri = FileProvider.getUriForFile(getContext(), "com.feige.pickphoto.fileprovider", outputImage);
        } else {
            //小于android 版本7.0（24）的场合
            imageUri = Uri.fromFile(outputImage);
        }

        //启动相机程序
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //MediaStore.ACTION_IMAGE_CAPTURE = android.media.action.IMAGE_CAPTURE
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
    }

    /**
     * 知乎加载图片库,加载手机中的图片
     */
    void goGallery() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(1)
                .gridExpectedSize(400)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(1001);
    }


    List<Uri> mSelected;

    //
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK) {//相机获得图片地址
            mSelected = Matisse.obtainResult(data);
            try {
                Bitmap bitmap = Objects.requireNonNull(FileUtil.getBitmapFormUri(getActivity(), mSelected.get(0)));
                String fileName = Matisse.obtainPathResult(data).get(0);
                if (!TextUtils.isEmpty(fileName) && null != callBack){
                    callBack.pictureBack(fileName);
                    dismiss();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (requestCode == SELECT_PIC_BY_TACK_PHOTO) {
            if (resultCode == RESULT_OK) {
                try {
                    // 将拍摄的照片显示出来
                    Bitmap bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
                    if (!TextUtils.isEmpty(imagePath) && null != bitmap && null != callBack){
                        callBack.pictureBack(imagePath);
                        dismiss();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 回调,把结果回调给获取图片的UI
     */
    public interface CallBack {
        void pictureBack(String imagePath);
    }

    public void setCallBack(CallBack callBack) {
        if (null != callBack) this.callBack = callBack;
    }
}